<template>
  <div>
    <el-form ref="form" v-model="form" label-width="80px" inline>
      <el-form-item label="创建时间">
        <el-date-picker
          type="date"
          placeholder="起始日期"
          v-model="form.startDate"
          value-format="yyyy-MM-dd"
          style="width: 150px"
        ></el-date-picker>
        <span style="margin: 0 5px">-</span>
        <el-date-picker
          placeholder="截止日期"
          v-model="form.endDate"
          value-format="yyyy-MM-dd"
          style="width: 150px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.prevent="searchInfo()">搜索</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    <template>
      <div v-for="order in pageInfo.list" :key="order.id">
        <p>
          <span>订单号：{{ order.serialNumber }}</span>
          <span>创建时间：{{ order.createTime }}</span>
        </p>
        <p>
          <span>用户名：{{ order.loginName }}</span>
          <span>用户地址：{{ order.userAddress }}</span>
        </p>
        <el-table :data="order.orderDetails" border style="width: 100%">
          <el-table-column label="序号" width="80">
            <template slot-scope="scope">
              {{ (form.pageNum - 1) * form.pageSize + scope.$index + 1 }}
              <!-- 从 1 开始计数 -->
            </template>
          </el-table-column>
          <el-table-column
            prop="productName"
            label="商品名称"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="quantity"
            label="数量"
            width="100"
          ></el-table-column>
          <el-table-column prop="cost" label="价格(元)" width="200">
          </el-table-column>
        </el-table>
        <p>
          <span>总消费(元)：{{ order.cost }}</span>
          <el-row>
            <el-button
              v-if="order.status == 0"
              type="primary"
              plain
              @click.once="toPay(order)"
              >去支付</el-button
            >
            <el-button
              v-if="order.status == 1"
              type="primary"
              plain
              @click="toRefund(order)"
              >去退款</el-button
            >
            <el-button
              type="primary"
              v-if="order.status != 0"
              plain
              @click.once="delOrder(order.id)"
              >删除订单</el-button
            >
          </el-row>
        </p>
      </div>
    </template>
    <div class="block">
      <el-pagination
        @size-change="changePageSize"
        @current-change="changePageNum"
        :current-page="form.pageNum"
        :page-sizes="[5, 10]"
        :page-size="form.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :visible.sync="payDialogVisible"
      title="选择支付方式"
      width="30%"
    >
      <div class="payment-options">
        <el-button type="primary" icon="el-icon-alipay" @click="payWithAlipay">
          支付宝支付
        </el-button>
        <el-button type="success" icon="el-icon-wechat" @click="payWithWechat">
          微信支付
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: "myOrderPage",
  data() {
    return {
      pageInfo: {},
      form: {
        searchUserName: "",
        startDate: "",
        endDate: "",
        pageNum: 1,
        pageSize: 5,
      },
      isAll: "",
      userId: "",
      payDialogVisible: false, // 支付对话框的可见性
      currentOrder: null,
    };
  },
  created() {
    if (this.$router.currentRoute.path == "/managerIndex/manageOrder/myOrder") {
      this.isAll = 0;
      const userJson = window.sessionStorage.getItem("user");
      if (userJson) {
        const user = JSON.parse(userJson);
        this.userId = user.id;
      }
    }
  },

  methods: {
    searchInfo() {
      this.$axios
        .get("api/order/page", {
          params: {
            userId: this.userId,
            isAll: this.isAll,
            startDate: this.form.startDate,
            endDate: this.form.endDate,
            pageNum: this.form.pageNum,
            pageSize: this.form.pageSize,
          },
        })
        .then((response) => {
          this.pageInfo = response.data.pageInfo;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    changePageNum(newPageNum) {
      this.form.pageNum = newPageNum;
      this.searchInfo();
    },
    toRefund(order) {
      if(order.tradeType==1){
        this.$axios
        .post("api/zfb/refund", {
          serialNumber:order.serialNumber,
          cost:order.cost
        })
        .then((response) => {
          // this.pageInfo = response.data.pageInfo;
          if (response.data.refundStatus) {
            alert("退款成功！");
            this.searchInfo();
          } else {
            alert("退款失败！");
          }
        })
        .catch((error) => {
          console.log(error);
        });
      } 
      if(order.tradeType==11){
       alert("微信退款");
      }
    },
    delOrder(id) {
      if (confirm("确认删除订单吗？")) {
        this.$axios
          .get(`api/order/del/${id}`)
          .then((response) => {
            if (response.data.delStatus) {
              alert("删除成功");
              this.searchInfo();
            }
          })
          .catch((error) => {
            this.$message.error("删除失败");
            console.error(error);
          });
      }
    },
    changePageSize(newPageSize) {
      this.form.pageSize = newPageSize;
      this.searchInfo();
    },
    toPay(order) {
      this.currentOrder = order;
      this.payDialogVisible = true;
    },
    payWithAlipay() {
      this.$axios
        .post("api/zfb/pay", {
          serialNumber: this.currentOrder.serialNumber,
          cost: this.currentOrder.cost,
          loginName: this.currentOrder.loginName,
          headers: {
            Authorization: +this.token,
          },
        })
        .then((response) => {
          // this.pageInfo = response.data.pageInfo;
          console.log(response.data);
          var mydiv = document.createElement("div");
          mydiv.innerHTML = response.data;
          document.body.appendChild(mydiv);
          document.getElementsByName("punchout_form")[0].submit();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    payWithWechat() {
      this.$axios
        .post(
          "api/wx/zf",
          {
            serialNumber: this.currentOrder.serialNumber,
          },
          {
            headers: {
              Authorization: this.token,
            },
          }
        )
        .then((response) => {
          // 获取支付二维码的 URL
          this.payUrl = response.data.pay_url;
          this.$router.push({
                  name: 'weChatPay',
                  query: { url: this.payUrl ,serialNumber:this.currentOrder.serialNumber},
                })
        })
        .catch((error) => {
          console.error("支付请求失败", error);
          alert("支付请求失败，请稍后再试");
        });
    },
    delUser(id) {
      console.log(id);
    },
  },
  mounted() {
    this.searchInfo();
  },
};
</script>

<style>
.payment-options {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.payment-options .el-button {
  width: 45%;
  font-size: 16px;
  padding: 12px 0;
}

.payment-options .el-button:hover {
  cursor: pointer;
}
</style>
